package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.yxt.common.sort.MapComparator;
import com.yxt.common.sys.CommConstant;
import com.yxt.common.sys.StringUtil;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.ui.TextItemOnClickListener;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;
import com.yxt.model.Listener;

public class WaterStationListActivity extends Activity {
	private static final int MENU_ZHABA = Menu.FIRST+1;
	private static final int MENU_HEDAO = Menu.FIRST+2;
	private static final int MENU_SHUIKU = Menu.FIRST + 3;
	private static final int MENU_CHAOWEI = Menu.FIRST + 4;
	private static final int MENU_MAP = Menu.FIRST + 5;
	
	public static List<Map<String,String>> list = new ArrayList<Map<String,String>>();
	public static Map<String,String> headers = new HashMap<String,String>();
	private MapComparator comparator = new MapComparator();
	private String[] from = { "name", "time", "value","over"};
	private int[] to = {R.id.lbl1,R.id.lbl2,R.id.lbl3,R.id.lbl4};
	private String[] keys = {"code"};
	private String watertype = "";
	private String waterover = "";
	private TextView lblTitle;
	private ProgressDialog dialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.water_list);   //软件activity的布局	
		ActivityStackControlUtil.add(this);
		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		lblTitle = (TextView)findViewById(R.id.lblTitle);
		TextView lblTitle2 = (TextView)findViewById(R.id.lblTitle2);
		lblTitle2.setOnClickListener(new OnClickListener(){			
			public void onClick(View view) {
				fillListView("time");
			}
		});

		TextView lblTitle3 = (TextView)findViewById(R.id.lblTitle3);
		lblTitle3.setOnClickListener(new OnClickListener(){			
			public void onClick(View view) {
				fillListView("value");
			}
		});
		initComponent();
	}
	
	private void initComponent(){	
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{
					StringBuffer title = new StringBuffer();
					if (CommConstant.Water.WATER_OVER.equals(waterover)) {
						title.append("超汛");
					}
					title.append(headers.get("name")+ "(" + headers.get("value") + ")" );
					lblTitle.setText(title.toString());
					fillListView("");
					dialog.cancel();
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadStationList();
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}
	
	private void downloadStationList() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new WaterStationHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}
	}

	private InputStream getInputStream() throws IOException{
		if(StringUtil.isEmpty(watertype)) {
			Intent intent = getIntent();
			watertype = intent.getStringExtra("type");
			waterover = intent.getStringExtra("waterover");
		}
		String server = CommConstant.Sever.WATER_SERVER;
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"waterlocation.xml");
		} else {
			URL url = new URL(server + "water/StaList.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&type="+watertype+"&over="+waterover);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}

	private class WaterStationHandler extends DefaultHandler {
		public void startDocument() throws SAXException {
			list.clear();
			headers.clear();
			super.startDocument();
		}
		
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("station".equals(localName)) {
				Map<String, String> data = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				list.add(data);
			} else if ("count".equals(localName)) {
				for (int i = 0; i < attrs.getLength(); i++) {
					headers.put(attrs.getLocalName(i), attrs.getValue(i));
				}
			} else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}

	private void fillListView(String key) {
		if (!"".equals(key)) {
			comparator.setKey(key);
			Collections.sort(list, comparator);
		}
		
		Map<String,String> data = new HashMap<String,String>();
		data.put("type", watertype);
		List<Listener> items = new ArrayList<Listener>();
		for (int i = 0; i < from.length; i++) {
			Listener listener = new Listener(to[i],new TextItemOnClickListener(this, WaterStationDetailActivity.class,data));
			items.add(listener);
		}
		
		List<String> keylist = new ArrayList<String>();
		for (int i = 0; i < keys.length; i++) {
			keylist.add(keys[i]);
		}
		WaterTableAdapter adapter = new WaterTableAdapter(getApplication(),list,R.layout.water_list_item,from,to,items,keylist,new ImageOnClickListener());
		ListView lstWaterStation = (ListView) findViewById(R.id.lstWaterStation);
		lstWaterStation.setAdapter(adapter);		
	}
	
	private class WaterTableAdapter extends SimpleAdapter {
		private List<Map<String,String>> dataList;
		private List<Listener> itemListeners = new ArrayList<Listener>();
		private OnClickListener imageItemListener;
		private List<String> keyList = new ArrayList<String>();
		
		public WaterTableAdapter(Context context, List<Map<String,String>> data,int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			this.dataList = data;
		}

		public WaterTableAdapter(Context context, List<Map<String,String>> data,int resource, String[] from, int[] to, List<Listener> items, List<String> keys,OnClickListener imageItemListener) {
			super(context, data, resource, from, to);
			keyList.addAll(keys);
			itemListeners.addAll(items);
			this.dataList = data;	
			this.imageItemListener = imageItemListener;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			 View view = super.getView(position, convertView, parent);		 
			int colorPos = position % CommConstant.Config.DEFAULT_TABLE_COLORS.length;
			view.setBackgroundColor(CommConstant.Config.DEFAULT_TABLE_COLORS[colorPos]);
			//添加点击事件
			String over = dataList.get(position).get("over");
			ImageView image = (ImageView)view.findViewById(R.id.imgdetail);
			image.setOnClickListener(imageItemListener);
			//如果为空则默认为0
			if(StringUtil.isEmpty(over)) {
				over = "0";
			}
			//如果超标显示超标图片
			if (Double.parseDouble(over) > 0) {
				image.setImageResource(R.drawable.up);	
				image.setContentDescription(over);	
			} else if (Double.parseDouble(over) < 0) {
				image.setImageResource(R.drawable.down);
				image.setContentDescription("");	
			} else {
				image.setImageResource(R.drawable.nochg);
				image.setContentDescription("");	
			}
			
			Map<String,String> data = dataList.get(position);
			for (int i = 0; i< itemListeners.size(); i++) {
				Listener item = itemListeners.get(i);
				View v = view.findViewById(item.getId());
				TextItemOnClickListener listener = item.getListener();
				Map<String,String> params = new HashMap<String,String>();
				for (int k = 0; k < keyList.size(); k++) {
					String key = keyList.get(k);
					params.put(key,data.get(key));
				}
				listener.setParameters(params);
				v.setOnClickListener(listener);
			}	
			
			return view;
		}
	}
	
	private class ImageOnClickListener implements OnClickListener{				
		public void onClick(View view) {
			ImageView image = (ImageView)view;
			if (StringUtil.isEmpty(image.getContentDescription().toString())) {
				waterover = CommConstant.Water.WATER_ALL;
			} else {
				waterover = CommConstant.Water.WATER_OVER;
			}
			initComponent();
		}		
	}
	
	/**
	 * 创建底部菜单
	 * */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_ZHABA, 1, R.string.menu_zhaba);
		menu.add(0, MENU_HEDAO, 2, R.string.menu_hedao);
		menu.add(0, MENU_SHUIKU, 3, R.string.menu_shuiku);
		menu.add(0, MENU_CHAOWEI, 4, R.string.menu_chaowei);
		menu.add(0, MENU_MAP, 5, R.string.menu_map);
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * 点击底部菜单项时的处理
	 */
	public boolean onOptionsItemSelected(MenuItem item) {	
		Intent intent = new Intent();	
		switch (item.getItemId()) {
			case MENU_ZHABA:
				watertype = CommConstant.Water.ZB_TYPE;
				waterover = "";
				initComponent();
				return true;
			case MENU_HEDAO:
				watertype = CommConstant.Water.HD_TYPE;
				waterover = "";
				initComponent();
				return true;
			case MENU_SHUIKU:
				watertype = CommConstant.Water.SK_TYPE;
				waterover = "";
				initComponent();	
				return true;
			case MENU_CHAOWEI:
				watertype = CommConstant.Water.CW_TYPE;
				waterover = "";
				initComponent();	
				return true;
			case MENU_MAP:
				intent.setClass(getApplicationContext(), WaterStationMapActivity.class);
				intent.putExtra("type", watertype);
				startActivity(intent);	
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void onDestroy() {
		super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
}